#pragma once


#include <iostream>
#include <vector>
#include <string>
#include <cstring>
#include <cassert>
#include <ctime>
#include <memory>
#include <functional>
#include <unordered_map>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <signal.h>
#include <pthread.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/timerfd.h>
#include <sys/types.h>
#include <sys/eventfd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/epoll.h>

#define INF 0
#define DBG 1
#define ERR 2
#define LOG_LEVEL INF

//日志宏
#define LOG(LEVEL,format, ...) do{\
    if(LEVEL < LOG_LEVEL) break;\
    time_t t = time(nullptr);\
    struct tm* ltm = localtime(&t);\
    char tmp[32] = {0};\
    strftime(tmp,31,"%H:%M:%S",ltm);\
    fprintf(stdout,"[%p %s %s:%d] " format "\n",(void*)pthread_self(),tmp,__FILE__,__LINE__,##__VA_ARGS__);\
}while(0)

#define INF_LOG(format, ...) LOG(INF,format,##__VA_ARGS__)
#define DBG_LOG(format, ...) LOG(DBG,format,##__VA_ARGS__)
#define ERR_LOG(format, ...) LOG(ERR,format,##__VA_ARGS__)


const uint64_t BUFFER_DEFAULT_SIZE = 1024; 
class Buffer
{
private:
    std::vector<char> _buffer;//使用vector进行内存空间管理
    uint64_t _reader_idx;//读偏移
    uint64_t _write_idx;//写偏移

public:
    Buffer()
        :_reader_idx(0)
        ,_write_idx(0)
        ,_buffer(BUFFER_DEFAULT_SIZE)
    {}

    char* Begin(){ return &*_buffer.begin(); }
    //获取当前写入起始地址
    char* WritePosition()
    {
        return Begin() + _write_idx;
    }
    //获取当前读取起始地址
    char* ReadPosition()
    {
        return Begin() + _reader_idx;
    }
    //获取缓冲区末尾空闲空间大小
    uint64_t TailIdleSize()
    {
        return _buffer.size() - _write_idx;
    }
    //获取缓冲区起始空闲空间大小
    uint64_t HeadIdleSize()
    {
        return _reader_idx;
    }
    //获取可读数据大小
    uint64_t ReadAbleSize()
    {
        return _write_idx - _reader_idx;
    }
    //将读偏移向后移动
    void MoveReadOffset(uint64_t len)
    {
        if(len == 0) return;
        //必须小于可读空间大小
        assert(ReadAbleSize() >= len);
        _reader_idx += len;
    }
    //将写偏移向后移动
    void MoveWriteOffset(uint64_t len)
    {
        //必须小于尾部空间大小
        assert(TailIdleSize() >= len);
        _write_idx += len;
    }
    //确保可写空间足够len
    void EnsureWriteSpace(uint64_t len)
    {
        //尾部空间够，直接返回
        if(TailIdleSize() >= len) return;
        //总体空间够，将数据平移到最开始，为后面腾位置
        if(TailIdleSize() + HeadIdleSize() >= len)
        {
            //保存一下可读数据大小
            uint64_t rsz = ReadAbleSize();
            std::copy(ReadPosition(),ReadPosition() + rsz,Begin());//可读数据拷贝到起始位置
            _reader_idx = 0;
            _write_idx = rsz;
        }
        //不够，扩容
        else
        {
            _buffer.resize(_write_idx + len);
        }
    }
    //写入数据
    void Write(const void* date,uint64_t len)
    {
        //保证空间足够
        if(len == 0) return;
        EnsureWriteSpace(len);
        //将数据拷贝进去
        const char* d = (const char*)date;
        std::copy(d,d + len,WritePosition());
    }
    //写入数据并且更新写指针
    void WriteAndPush(const void* date,uint64_t len)
    {
        Write(date,len);
        MoveWriteOffset(len);
    }
    //写入一个字符串
    void WriteString(const std::string& date)
    {
        Write(date.c_str(),date.size());
    }
    //写入一个字符串并且更新写指针
    void WriteStringAndPush(const std::string& date)
    {
        WriteString(date);
        MoveWriteOffset(date.size());
    }
    //写入一个Buffer
    void WriteBuffer(Buffer& date)
    {
        Write(date.ReadPosition(),date.ReadAbleSize());
    }
    //写入一个Buffer并且更新写指针
    void WriteBufferAndPush(Buffer& date)
    {
        Write(date.ReadPosition(),date.ReadAbleSize());
        MoveWriteOffset(date.ReadAbleSize());
    }
    //读取数据
    void Read(void* buf,uint64_t len)
    {
        //获取数据的长度必须小于可读数据
        assert(len <= ReadAbleSize());
        std::copy(ReadPosition(),ReadPosition() + len,(char*)buf);
    }
    //读取数据并且更新读指针
    void ReadAndPop(void* buf,uint64_t len)
    {
        Read(buf,len);
        MoveReadOffset(len);
    }
    //读取一个长度为len的字符串
    std::string ReadString(uint64_t len)
    {
        assert(len <= ReadAbleSize());
        std::string str;
        str.resize(len);
        Read(&str[0],len);
        return str;
    }
    //读取一个长度为len的字符串并且更新读指针
    std::string ReadStringAndPop(uint64_t len)
    {
        assert(len <= ReadAbleSize());
        std::string str = ReadString(len);
        MoveReadOffset(len);
        return str;
    }

    //查找换行符
    char* FindCRLF()
    {
        char* res = (char*)memchr(ReadPosition(),'\n',ReadAbleSize());
        return res;
    }

    //获取一行字符串
    std::string GetLine()
    {
        //找到换行符位置
        char* pos = FindCRLF();
        if(pos == nullptr) return "";
        //+1是为了把换行符也取出来
        return ReadString(pos - ReadPosition() + 1);
    }
    //获取一行字符串并且更新读指针
    std::string GetLineAndPop()
    {
        std::string str = GetLine();
        MoveReadOffset(str.size());
        return str;
    }
    //清空缓冲区
    void Clear()
    {
        //偏移量归零
        _reader_idx = _write_idx = 0;
    }
};

const int MAX_LISTEN = 1024;
class Socket
{
private:
    int _sockfd;
public:
    Socket()
        :_sockfd(-1)
    {}
    Socket(int fd)
        :_sockfd(fd)
    {}
    ~Socket()
    {
        Close();
    }
    int Fd()
    {
        return _sockfd;
    }

    //创建套接字
    bool Create()
    {
        //int socket(int domain,int type,int protocol)
        //ipv4 字节流 TCP
        _sockfd = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
        if(_sockfd < 0)
        {
            ERR_LOG("CREATE SOCKET FAILED!!");
            return false;
        }
        return true;
        
    }
    //绑定地址信息
    bool Bind(const std::string& ip,uint16_t port)
    {
        //ipv4专用地址
        struct sockaddr_in addr;
        addr.sin_family = AF_INET;
        //将点分十进制ip地址转换为网络字节序(大端)                              //ipv4
        addr.sin_addr.s_addr = inet_addr(ip.c_str());
        //记得主机转网络序列
        addr.sin_port = htons(port);
        socklen_t len = sizeof(struct sockaddr_in);
        //bind时转换为通用协议地址
        int ret = bind(_sockfd,(struct sockaddr*)&addr,len);
        if(ret < 0)
        {
            ERR_LOG("BIND ADDRESS FAILED!!");
            return false;
        }
        return true;
    }
    //开始监听 
    bool Listen(int backlog = MAX_LISTEN)
    {
        int ret = listen(_sockfd,backlog);
        if(ret < 0)
        {
            ERR_LOG("SOCKET LISTEN FAILED!!");
            return false;
        }
        return true;
    }
    //向服务器发起连接
    bool Connect(const std::string& ip,uint16_t port)
    {
        struct sockaddr_in addr;
        addr.sin_family = AF_INET;
        addr.sin_addr.s_addr = inet_addr(ip.c_str());
        addr.sin_port = htons(port);
        socklen_t len = sizeof(struct sockaddr_in);
        int ret = connect(_sockfd,(struct sockaddr*)&addr,len);
        if(ret < 0)
        {
            ERR_LOG("CONNECT SERVER FAILED!!");
            return false;
        }
        return true;
    }
    //获取新连接
    int Accept()
    {   
        //不关心客户端，后两个参数设为空
        int newfd = accept(_sockfd,nullptr,nullptr);
        if(newfd < 0)
        {
            ERR_LOG("SOCKET ACCEPT FAILED!!");
            return -1;
        }
        return newfd;
    }
    //接收数据
    ssize_t Recv(void* buf,size_t len,int flag = 0)
    {
        ssize_t ret = recv(_sockfd,buf,len,flag);
        //ret == 0 连接断开
        if(ret <= 0)
        {
            //EAGAIN,没有数据，非阻塞模式才会出现这个错误
            //EINTR,阻塞等待时被打断
            if(errno == EAGAIN || errno == EINTR)
            {
                return 0;//这次没有收到数据
            }
            ERR_LOG("SOCKET RECV FAILED!!");
            return -1;
        }
        return ret;//返回实际接收长度
    }
    ssize_t NonBlockRecv(void* buf,size_t len)
    {
        return Recv(buf,len,MSG_DONTWAIT);//非阻塞模式
    }
    //发送数据
    ssize_t Send(const void* buf,size_t len,int flag = 0)
    {
        ssize_t ret = send(_sockfd,buf,len,flag);
        if(ret < 0)
        {
            if(errno == EAGAIN || errno == EINTR)
            {
                return 0;
            }
            ERR_LOG("SOCKET SEND FAILED!!");
            return -1;
        }
        return ret;//实际发送长度
    }
    ssize_t NonBlockSend(const void* buf,size_t len)
    {
        return Send(buf,len,MSG_DONTWAIT);
    }
    //关闭套接字
    void Close()
    {
        if(_sockfd != -1)
        {
            close(_sockfd);
            _sockfd = -1;
        }
    }
    //创建一个服务器连接
    bool CreateServer(uint16_t port,const std::string& ip = "0.0.0.0",bool block_flag = false)
    {
        //1.创建套接字 2.设置非阻塞 3.设置地址重用 4.绑定地址 5.开始监听
        if(Create() == false) return false;
        if(block_flag) Nonblock();
        //绑定前开启地址重用
        ReuseAddress();
        if(Bind(ip,port) == false) return false;
        if(Listen() == false) return false;
        return true;
    }
    //创建一个客户端连接
    bool CreateClient(uint16_t port,const std::string& ip)
    {
        //1.创建套接字 2.连接服务器
        if(Create() == false) return false;
        if(Connect(ip,port) == false) return false;
        return true;
    }
    //设置套接字选项，开启地址端口重用
    void ReuseAddress()
    {
        // int setsockopt(int fd, int leve, int optname, void *val, int vallen)
        int val = 1;
        //开启地址端口重用
        setsockopt(_sockfd,SOL_SOCKET,SO_REUSEADDR,(void*)&val,sizeof(int));
        val = 1;
        //允许多个进程绑定相同ip+端口
        setsockopt(_sockfd,SOL_SOCKET,SO_REUSEPORT,(void*)&val,sizeof(int));
    }
    //设置套接字属性，设置为非阻塞
    void Nonblock()
    {
        //int fcntl(int fd, int cmd, ... /* arg */ );
        int flag = fcntl(_sockfd,F_GETFL,0);
        fcntl(_sockfd,F_SETFL,flag | O_NONBLOCK);
    }
};

class Poller;
class EventLoop;

class Channel
{
private:
    int _fd;
    EventLoop* _loop;
    uint32_t _events;  //当前需要监控的事件
    uint32_t _revents; //当前连接触发的事件
    using EventCallback = std::function<void()>;
    EventCallback _read_callback;   //可读事件被触发的回调函数
    EventCallback _write_callback;  //可写事件被触发的回调函数
    EventCallback _error_callback;  //错误事件被触发的回调函数
    EventCallback _close_callback;  //连接断开事件被触发的回调函数
    EventCallback _event_callback;  //任意事件被触发的回调函数

public:
    Channel(EventLoop* loop,int fd)
        :_fd(fd)
        ,_events(0)
        ,_revents(0)
        ,_loop(loop)
    {}
    int Fd()
    {
        return _fd;
    }
    //获取想要监控的事件
    uint32_t Events()
    {
        return _events;
    }
    //设置实际就绪事件
    void SetEvents(uint32_t events)
    {
        _revents = events;
    }
    void SetReadCallback(const EventCallback& cb)
    {
        _read_callback = cb;
    }
    void SetWriteCallback(const EventCallback& cb)
    {
        _write_callback = cb;
    }
    void SetErrorCallback(const EventCallback& cb)
    {
        _error_callback = cb;
    }
    void SetCloseCallback(const EventCallback& cb)
    {
        _close_callback = cb;
    }
    void SetEventCallback(const EventCallback& cb)
    {
        _event_callback = cb;
    }
    //当前是否监控了可读
    bool ReadAble()
    {
        return (_events & EPOLLIN);
    }        
    //当前是否可写
    bool WriteAble()
    {
        return (_events & EPOLLOUT);
    }    
    //启动读事件监控   
    void EnableRead()
    {
        _events |= EPOLLIN;
        Update();
    }  
    //启动写事件监控
    void EnableWrite()
    {
        _events |= EPOLLOUT;
        Update();
    }  
    //关闭读事件监控
    void DisableRead()
    {
        _events &= ~EPOLLIN;
        Update();
    }     
    //关闭写事件监控
    void DisableWrite()
    {
        _events &= ~EPOLLOUT;
        Update();
    }
    //关闭所有事件
    void DisableAll()
    {
        _events = 0;
        Update();
    }
    //移除监控
    void Remove();
    void Update();
    //事件处理，一旦触发事件调用它，用它来判断自己触发了什么事件，该去哪处理       
    void HandleEvent()
    {
        // 1. 优先处理错误事件：连接已致命，无需也无权再操作数据
        if (_revents & EPOLLERR) {
            if (_error_callback) _error_callback();
            // 错误通常是致命的，处理后直接返回，不再触发其他回调
            if (_event_callback) _event_callback(); // 错误事件也触发通用回调
            return;
        }

        // 2. 处理挂起事件：连接已完全断开且缓冲区数据已经读完
        if ((_revents & EPOLLHUP) && !(_revents & EPOLLIN)) {
            if (_close_callback) _close_callback();
            if (_event_callback) _event_callback(); // 关闭事件也触发通用回调
            return;
        }

        // 3. 处理读事件（包括普通数据、对端半关闭后的剩余数据）
        if (_revents & (EPOLLIN | EPOLLPRI | EPOLLRDHUP)) {
            if (_read_callback) _read_callback();
        }

        // 4. 处理写事件
        if (_revents & EPOLLOUT) {
            if (_write_callback) _write_callback();
        }

        // 5. 最后处理通用事件：任何事件触发（只要执行到这里）都会调用
        // 注意：由于错误和挂起事件已在上方返回，通用事件在那里被提前触发。
        // 而对于读/写事件，它在这里被触发。
        if (_event_callback) _event_callback();
    }    
};

const int MAX_EPOLLEVENTS = 1024;
class Poller
{
private:
    int _epfd;
    struct epoll_event _evs[MAX_EPOLLEVENTS];
    std::unordered_map<int,Channel*> _channels;

    //对epoll的直接操作
    void Update(Channel* channel,int op)
    {
        // int epoll_ctl(int epfd, int op,  int fd,  struct epoll_event *ev);
        int fd = channel->Fd();
        struct epoll_event ev;
        ev.data.fd = fd;
        ev.events = channel->Events();
        int ret = epoll_ctl(_epfd,op,fd,&ev);
        if(ret < 0)
        {
            ERR_LOG("EPOLLCTL FAILED!!");
        }
    }
    //判断一个Channel是否已经添加了事件监控
    bool HasChannel(Channel* channel)
    {
        auto it = _channels.find(channel->Fd());
        if(it == _channels.end())
        {
            return false;
        }
        return true;
    }
public:
    Poller()
    {
        _epfd = epoll_create(MAX_EPOLLEVENTS);
        if(_epfd < 0)
        {
            ERR_LOG("EPOLL CREATE FAILED!!");
            abort();//直接退出
        }
    }
    //添加或者修改监控事件
    void UpdateEvent(Channel* channel)
    {
        bool ret = HasChannel(channel);
        if(ret == false)
        {
            //不存在则添加
            _channels.insert(std::make_pair(channel->Fd(),channel));
            Update(channel,EPOLL_CTL_ADD);
        }
        //存在则修改
        Update(channel,EPOLL_CTL_MOD);
    }
    //移除监控
    void RemoveEvent(Channel* channel)
    {
        auto it = _channels.find(channel->Fd());
        if(it != _channels.end())
        {
            _channels.erase(it);
        }
        Update(channel,EPOLL_CTL_DEL);
    }
    //开始监控，返回活跃连接
    void Poll(std::vector<Channel*>* active)
    {
        // int epoll_wait(int epfd, struct epoll_event *evs, int maxevents, int timeout)
        int nfds = epoll_wait(_epfd,_evs,MAX_EPOLLEVENTS,-1);//阻塞模式
        if(nfds < 0)
        {
            if(errno == EINTR)
            {
                return;
            }
            ERR_LOG("EPOLL WAIT ERROR:%s",strerror(errno));
            abort();
        }

        for(int i = 0;i < nfds;i++)
        {
            auto it = _channels.find(_evs[i].data.fd);
            assert(it != _channels.end());
            it->second->SetEvents(_evs[i].events);//设置实际就绪事件
            active->push_back(it->second);
        }
    }
};

using TaskFunc = std::function<void()>;
using ReleaseFunc = std::function<void()>;
class TimerTask
{
private:
    uint64_t _id; // 定时器的id
    uint32_t _timeout; //定时任务的超时时间
    bool _canceled; // 定时任务是否被取消
    TaskFunc _task_cb; // 定时器对象要执行的定时任务
    ReleaseFunc _release; //用于删除TimerWheel中保存的定时器对象信息

public:
    TimerTask(uint64_t id,uint32_t timeout, const TaskFunc& cb)
        :_id(id)
        ,_timeout(timeout)
        ,_task_cb(cb)
        ,_canceled(false)
    {}

    ~TimerTask()
    {
        if(_canceled == false) _task_cb();
        _release();
    }

    void Cancel()
    {
        _canceled = true;
    }

    void SetRelease(const ReleaseFunc& cb)
    {
        _release = cb;
    }

    uint32_t DelayTime()
    {
        return _timeout;
    }
};

class TimerWheel
{
private:
    using WeakTask = std::weak_ptr<TimerTask>;
    using PtrTask = std::shared_ptr<TimerTask>;

    int _tick; //当前的秒针，秒针走到哪，就释放哪，执行哪的任务
    int _capacity; // 时间轮的最大容量，也就是最大延迟时间

    std::vector<std::vector<PtrTask>> _wheel; // 时间轮，一个二维数组
    std::unordered_map<uint64_t,WeakTask> _timers; // id to Weaktask

    EventLoop* _loop;
    int _timerfd;
    std::unique_ptr<Channel> _timer_channel;

private:

    void RemoveTimer(uint64_t id)
    {
        auto it = _timers.find(id);
        if(it != _timers.end())
        {
            _timers.erase(it);
        }   
    }

    uint64_t ReadTimerfd()
    {
        uint64_t times;
        //read读到的数据就是上一次read后的超时次数
        int ret = read(_timerfd,&times,sizeof(times));
        if(ret < 0)
        {
            ERR_LOG("READ TIMERFD FAILED!!");
            abort();
        }
        return times;
    }

    //秒针往后走一部，这个函数应该每秒执行一次;
    void RunTimerTask()
    {
        _tick = (_tick + 1) % _capacity;
        _wheel[_tick].clear(); // 清空指定位置的数组,就把在该位置的所有shared_ptr全部释放掉了
    }

    //时间到了
    void OnTime()
    {
        //根据实际超时的次数，执行对应的超时任务
        uint64_t times = ReadTimerfd();
        for(int i = 0;i < times;i++)
        {
            RunTimerTask();
        }
    }

    void TimerAddInLoop(uint64_t id,uint32_t timeout,const TaskFunc& cb)
    {
        PtrTask ptr(new TimerTask(id,timeout,cb));
        ptr->SetRelease(std::bind(&TimerWheel::RemoveTimer,this,id));
        int pos = (_tick + timeout) % _capacity; // 找到需要存放的位置
        _wheel[pos].push_back(ptr);
        _timers[id] = WeakTask(ptr);
    }

    void TimerRefreshInLoop(uint64_t id)
    {
        //通过timers中的WeakTask构造一个shareed_ptr出来，添加到轮子的新位置中
        auto it = _timers.find(id);
        if(it == _timers.end())
        {
            return;
        }

        PtrTask ptr = it->second.lock();
        int timeout = ptr->DelayTime();
        int pos = (_tick + timeout) % _capacity;
        _wheel[pos].push_back(ptr);
    }

    void TimerCancelInLoop(uint64_t id)
    {
        auto it = _timers.find(id);
        if(it == _timers.end())
        {
            return;
        }

        PtrTask ptr = it->second.lock();
        if(ptr) ptr->Cancel();
    }


    static int CreateTimerFd()
    {
        int timerfd = timerfd_create(CLOCK_MONOTONIC,0);
        if(timerfd < 0)
        {
            ERR_LOG("CREATE TIMERFD FAILED!!");
            abort();
        }
        //int timerfd_settime(int fd, int flags, struct itimerspec *new, struct itimerspec *old);
        struct itimerspec itime;
        itime.it_value.tv_nsec = 0;
        itime.it_value.tv_sec = 1;//第一次超时时间
        itime.it_interval.tv_nsec = 0;
        itime.it_interval.tv_sec = 1;//之后的周期超时时间
        timerfd_settime(timerfd,0,&itime,nullptr);
        return timerfd;
    }

public:
    TimerWheel(EventLoop* loop)
        :_capacity(60)
        ,_tick(0)
        ,_wheel(_capacity)
        ,_loop(loop)
        ,_timerfd(CreateTimerFd())
        ,_timer_channel(new Channel(_loop,_timerfd))
    {
        _timer_channel->SetReadCallback(std::bind(&TimerWheel::OnTime,this));
        _timer_channel->EnableRead();
    }

    //添加时间任务
    void TimerAdd(uint64_t id,uint32_t timeout,const TaskFunc& cb);
    //刷新某定时任务
    void TimerRefresh(uint64_t id);
    //取消某定时任务
    void TimerCancel(uint64_t id);

    //这个接口存在线程安全问题，不能被使用者调用，只能在模块内使用
    bool HasTimer(uint64_t id)
    {
        auto it = _timers.find(id);
        if(it == _timers.end())
        {
            return false;
        }
        return true;
    }
};

class EventLoop
{
private:
    using Functor = std::function<void()>;
    int _event_fd;                          //eventfd唤醒IO事件监控可能导致的阻塞
    std::unique_ptr<Channel> _event_channel;
    std::thread::id _thread_id;             //线程ID
    Poller _poller;                         //进行所有描述符的事件监控
    std::vector<Functor> _tasks;            //任务池
    std::mutex _mutex;                      //实现任务池操作的线程安全

    TimerWheel _timer_wheel;                //定时器模块
private:
    void RunAllTask()
    {
        std::vector<Functor> tmp;
        {
            std::unique_lock<std::mutex> _lock(_mutex);
            _tasks.swap(tmp);
        }

        for(auto& f : tmp)
        {
            f();
        }
    }
    static int CreateEventFd()
    {
        int efd = eventfd(0,EFD_CLOEXEC | EFD_NONBLOCK);
        if(efd < 0)
        {
            ERR_LOG("CREATE EVENTFD FAILED!!");
            abort();
        }
        return efd;
    }
    void ReadEventFd()
    {
        uint64_t res = 0;
        int ret = read(_event_fd,&res,sizeof(res));
        if(ret < 0)
        {
            //被信号打断或者没读到数据
            if(errno == EINTR || errno == EAGAIN)
            {
                return;
            }
            ERR_LOG("READ EVENTFD FAILED!!");
            abort();
        }
    }
    void WeakUpEventFd()
    {
        uint64_t val = 1;
        int ret = write(_event_fd,&val,sizeof(val));
        if(ret < 0)
        {
            if(errno == EINTR)
            {
                return;
            }
            ERR_LOG("WRITE EVENTED FAILED!!");
            abort();
        }
    }

public:
    EventLoop()
        :_thread_id(std::this_thread::get_id())
        ,_event_fd(CreateEventFd())
        ,_event_channel(new Channel(this,_event_fd))
        ,_timer_wheel(this)
    {
        //给eventfd添加可读回调函数，读取eventfd事件通知次数
        _event_channel->SetReadCallback(std::bind(&EventLoop::ReadEventFd,this));
        //启动evetnfd的读事件监控
        _event_channel->EnableRead();
    }
    //判断将要执行的任务是否处于当前线程，是则执行，不是则压入队列
    void RunInLoop(const Functor& cb)
    {
        if(IsInLoop())
        {
            cb();
            return;
        }
        QueueInLoop(cb);
        return;
    }
    void AssertInLoop()
    {
        assert(_thread_id == std::this_thread::get_id());
    }
    //将操作压入任务池
    void QueueInLoop(const Functor& cb)
    {
        {
            std::unique_lock<std::mutex> _lock(_mutex);
            _tasks.push_back(cb);
        }
        //唤醒可能因为没有事件就绪而导致的epoll阻塞
        //给eventfd写入一个数据
        WeakUpEventFd();
    }
    //判断当前线程是否是EventLoop的对应线程
    bool IsInLoop()
    {
        return _thread_id == std::this_thread::get_id();
    }
    //添加/修改描述符的事件监控
    void UpdateEvent(Channel* channel)
    {
        return _poller.UpdateEvent(channel);
    }
    //删除描述符的事件
    void RemoveEvent(Channel* channel)
    {
        return _poller.RemoveEvent(channel);
    }
    //事件监控 -----》就绪事件处理-----》执行任务
    void Start()
    {
        while(1)
        {
            //事件监控
            std::vector<Channel*> actives;
            _poller.Poll(&actives);

            //事件处理
            for(auto& channel : actives)
            {
                channel->HandleEvent();
            }

            //执行任务
            RunAllTask();
        }
    }

    void TimerAdd(uint64_t id,uint32_t timeout,const TaskFunc& cb)
    {
        _timer_wheel.TimerAdd(id,timeout,cb);
    }

    void TimerRefresh(uint64_t id)
    {
        _timer_wheel.TimerRefresh(id);
    }

    void TimerCancel(uint64_t id)
    {
        _timer_wheel.TimerCancel(id);
    }

    bool HasTimer(uint64_t id)
    {
        return _timer_wheel.HasTimer(id);
    }
};

class LoopThread
{
private:
    //这两个用于实现_loop获取同步关系,避免因为线程创建了,在_loop实例化之前去获取_loop
    std::mutex _mutex;                  //互斥锁
    std::condition_variable _cond;      //条件变量

    EventLoop* _loop;                   //EventLoop指针变量，这个对象需要在线程内部进行实例化
    std::thread _thread;                //EventLoop对应的线程
private:
    //实例化EventLoop对象,唤醒_cond上可能阻塞的线程，并且开始运行EventLoop模块的功能
    void ThreadEntry()
    {
        EventLoop loop;
        {
            //加锁
            std::unique_lock<std::mutex> lock(_mutex);
            _loop = &loop;
            _cond.notify_all();
        }
        loop.Start();
    }
public:
    //创建线程，设定线程入口函数
    LoopThread()
        :_loop(nullptr)
        ,_thread(std::thread(&LoopThread::ThreadEntry,this))
    {}
    //返回当前线程关联的EventLoop对象指针
    EventLoop* GetLoop()
    {
        EventLoop* loop = nullptr;
        {
            std::unique_lock<std::mutex> lock(_mutex);
            _cond.wait(lock,[&](){ return _loop != nullptr; });
            loop = _loop;
        }
        return loop;
    }
};

class LoopThreadPool
{
private:
    int _thread_count;                      //线程数量
    int _next_idx;                          //下一个loop的下标
    EventLoop* _baseloop;                   //主Loop，当_thread_count为0，就只使用它
    std::vector<LoopThread*> _threads;      //保存所有LoopThread对象
    std::vector<EventLoop*> _loops;         //保存所有EventLoop对象,baseloop除外

public:
    LoopThreadPool(EventLoop* baseloop)
        :_thread_count(0)
        ,_next_idx(0)
        ,_baseloop(baseloop)
    {}

    //设置线程数量
    void SetThreadCount(int count)
    {
        _thread_count = count;
    }
    //创建所有的从属线程
    void Create()
    {
        if(_thread_count > 0)
        {
            _threads.resize(_thread_count);
            _loops.resize(_thread_count);
        }

        for(int i = 0;i < _thread_count;i++)
        {
            _threads[i] = new LoopThread();
            _loops[i] = _threads[i]->GetLoop();
        }
    }
    //下一个Loop
    EventLoop* NextLoop()
    {
        if(_thread_count == 0)
        {
            return _baseloop;
        }
        _next_idx = (_next_idx + 1) % _thread_count;
        return _loops[_next_idx];
    }
};

class Any
{
private:
    class holder
    {
    public:
        virtual ~holder() {};
        virtual const std::type_info &type() = 0; // 纯虚函数，必须重写
        virtual holder* clone() = 0;
    };

    template <class T>
    class placeholder : public holder
    {
    public:
        placeholder(const T& val)
            :_val(val)
        {}

        //获取类型
        virtual const std::type_info& type()
        {
            return typeid(T);
        }

        //根据当前对象自身，克隆出一个新的子类
        virtual holder* clone()
        {
            return new placeholder(_val);
        }

        T _val;
    };

    holder* _content;

public:
    Any()
    :_content(nullptr)
    {}

    template<class T>
    Any(const T& val)
        :_content(new placeholder<T>(val))
    {}

    Any(const Any& other)
        :_content(other._content ? other._content->clone() : nullptr)
    {}

    ~Any()
    {
        delete _content;
    }

    Any& swap(Any& other)
    {
        std::swap(_content,other._content);
        return *this;
    }

    //返回子类对象保存数据的指针
    template<class T>
    T* get()
    {
        assert(typeid(T) == _content->type());
        return &((placeholder<T>*)_content)->_val;
    }

    //赋值运算符重载
    template<class T>
    Any& operator=(const T& val)
    {
        Any(val).swap(*this);
        return *this;
    }

    Any& operator=(const Any& other)
    {
        Any(other).swap(*this);
        return *this;
    }
};

class Connection;
typedef enum 
{
    DISCONNECTED,   //连接关闭
    CONNECTING,     //连接建立成功，待处理
    CONNECTED,      //连接建立完成，各种设置已经完成
    DISCONNECTING   //待关闭状态
} ConnStatu;
using PtrConnection = std::shared_ptr<Connection>;
class Connection : public std::enable_shared_from_this<Connection>
{
private:
    uint64_t _conn_id;              //连接的唯一id，便于连接的管理和查找
    //uint64_t _timer_id;           //定时器的ID,也是唯一的,这里为了方便简化操作，使用_conn_id
    int _sockfd;                    //连接关联的文件描述符
    bool _enable_inactive_release;  //是否启动非活跃销毁,默认为false
    EventLoop* _loop;               //连接所关联的一个EventLoop
    ConnStatu _statu;               //连接的状态
    Socket _socket;                 //套接字操作管理
    Channel _channel;               //连接的事件管理
    Buffer _in_buffer;              //输入缓冲区,存放从socket中读取到的数据
    Buffer _out_buffer;             //输出缓冲区,存放要发送给对端的数据
    Any _context;                   //请求的接收处理上下文

    // 这4个回调是让组件使用者来设置的
    using ConnectedCallback = std::function<void(const PtrConnection&)>;
    using MessageCallback = std::function<void(const PtrConnection&,Buffer*)>;
    using ClosedCallback = std::function<void(const PtrConnection&)>;
    using AnyEventCallback = std::function<void(const PtrConnection&)>;
    ConnectedCallback _connected_callback;
    MessageCallback _message_callback;
    ClosedCallback _closed_callback;
    AnyEventCallback _event_callback;
    // 组件内部的连接关闭回调
    ClosedCallback _server_closed_callback;

private:
    //五个channel事件回调
    //描述符可读事件触发后调用的函数，接收socket数据放到接收缓冲区中，然后调用_message_callback
    void HandleRead()
    {
        //接收socket的数据，放入缓冲区
        char buf[65536];
        ssize_t ret = _socket.NonBlockRecv(buf,65535);
        if(ret < 0)
        {
            //出错了，不能直接关闭
            return ShutdownInLoop();
        }
        //将数据放入输入缓冲区，记得写偏移
        _in_buffer.WriteAndPush(buf,ret);
        //调用_message_callback进行业务处理
        if(_in_buffer.ReadAbleSize() > 0)
        {
            return _message_callback(shared_from_this(),&_in_buffer);
        }
    }
    void HandleWrite()
    {
        //_out_buffer中保存的数据就是要发送的数据
        ssize_t ret = _socket.NonBlockSend(_out_buffer.ReadPosition(),_out_buffer.ReadAbleSize());
        if(ret < 0)
        {
            //发送错误就该关闭连接了,但得把缓冲区的数据处理完
            if(_in_buffer.ReadAbleSize() > 0)
            {
                _message_callback(shared_from_this(),&_in_buffer);
            }
            //实际的关闭释放操作
            return Release();
        }
        //不要忘记，将读指针向后偏移
        _out_buffer.MoveReadOffset(ret);
        if(_out_buffer.ReadAbleSize() == 0)
        {
            //没有数据待发送了，关闭写监控
            _channel.DisableWrite();
            //如果当前状态是待关闭，可以释放连接了
            if(_statu == DISCONNECTING)
            {
                return Release();
            }
        }
    }
    void HandleClose()
    {
        //一旦挂断，套接字什么都干不了，因此有数据处理就处理一下，之后关闭连接
        if(_in_buffer.ReadAbleSize() > 0)
        {
            _message_callback(shared_from_this(),&_in_buffer);
        }
        return Release();
    }
    void HandleError()
    {
        return HandleClose();
    }
    void HandleEvent()
    {
        //刷新事件活跃度
        if(_enable_inactive_release == true)
        {
            _loop->TimerRefresh(_conn_id);
        }
        if(_event_callback)
        {
            _event_callback(shared_from_this());
        }
    }
    //连接获取后，所处状态下要进行各种设置，启动读监控，调用回调函数
    void EstablishedInLoop()
    {
        //修改连接状态
        assert(_statu == CONNECTING);
        _statu = CONNECTED;
        //启动读事件监控，这里不能在构造函数中启动，因为可能刚启动就有事件到来，需要刷新定时任务，但是定时任务还没添加
        _channel.EnableRead();
        //调用回调函数
        if(_connected_callback)
        {
            _connected_callback(shared_from_this());
        }
    }
    //实际的释放接口
    void ReleaseInLoop()
    {
        //修改连接状态
        _statu = DISCONNECTED;
        //移除连接的事件监控
        _channel.Remove();
        //关闭文件描述符
        _socket.Close();
        //如果当前定时任务器中还有任务，则取消任务
        if(_loop->HasTimer(_conn_id))
        {
            CancelInactiveReleaseInLoop();
        }
        //调用组件使用者的关闭回调函数
        if(_closed_callback)
        {
            _closed_callback(shared_from_this());
        }
        //移除服务器内部的管理信息
        if(_server_closed_callback)
        {
            _server_closed_callback(shared_from_this());
        }
    }
    //这并不是实际的发送接口，只是把数据放到了发送缓冲区，启动了可写事件监控
    void SendInLoop(Buffer &buf)
    {
        if(_statu == DISCONNECTED) return;
        _out_buffer.WriteBufferAndPush(buf);
        if(_channel.WriteAble() == false)
        {
            _channel.EnableWrite();
        }
    }
    //这个接口并非实际的连接释放，需判断有没有数据待处理，待发送
    void ShutdownInLoop()
    {
        //设置连接为半关闭
        _statu = DISCONNECTING;
        //有数据待处理
        if(_in_buffer.ReadAbleSize() > 0)
        {
            if(_message_callback)
            {
                _message_callback(shared_from_this(),&_in_buffer);
            }
        }
        //有数据待发送
        if(_out_buffer.ReadAbleSize() > 0)
        {
            if(_channel.WriteAble() == false)
            {
                _channel.EnableWrite();
            }
        }

        //如果数据发送完毕
        if(_out_buffer.ReadAbleSize() == 0)
        {
            Release();
        }
        
    }
    //启动非活跃释放规则
    void EnableInactiveReleaseInLoop(int sec)
    {
        //将判断标志置为true
        _enable_inactive_release = true;
        //如果定时任务已经存在就刷新
        if(_loop->HasTimer(_conn_id))
        {
            return _loop->TimerRefresh(_conn_id);
        }
        //不存在则添加
        _loop->TimerAdd(_conn_id,sec,std::bind(&Connection::Release,this));
    }
    void CancelInactiveReleaseInLoop()
    {
        _enable_inactive_release = false;
        if(_loop->HasTimer(_conn_id))
        {
            _loop->TimerCancel(_conn_id);
        }
    }
    void UpgradeInLoop(const Any& context,const ConnectedCallback& conn,const MessageCallback& msg,
                 const ClosedCallback& closed,const AnyEventCallback& event)
    {
        _context = context;
        _connected_callback = conn;
        _message_callback = msg;
        _closed_callback = closed;
        _event_callback = event;
    }
public:
    Connection(EventLoop* loop,uint64_t conn_id,int sockfd)
        :_loop(loop)
        ,_conn_id(conn_id)
        ,_sockfd(sockfd)
        ,_enable_inactive_release(false)
        ,_channel(loop,_sockfd)
        ,_statu(CONNECTING)
        ,_socket(_sockfd)
    {
        _channel.SetCloseCallback(std::bind(&Connection::HandleClose,this));
        _channel.SetReadCallback(std::bind(&Connection::HandleRead,this));
        _channel.SetWriteCallback(std::bind(&Connection::HandleWrite,this));
        _channel.SetEventCallback(std::bind(&Connection::HandleEvent,this));
        _channel.SetErrorCallback(std::bind(&Connection::HandleError,this));
    }
    ~Connection()
    {
        DBG_LOG("CONNECTION FREE");
    }
    int Fd()
    {
        return _sockfd;
    }
    uint64_t Id()
    {
        return _conn_id;
    }
    //是否处于connected状态
    bool Connected()
    {
        return _statu == CONNECTED;
    }
    //设置上下文，连接建立完成时调用
    void SetContext(const Any& context)
    {
        _context = context;
    }
    //获取上下文,返回的是指针
    Any* GetContext()
    {
        return &_context;
    }
    void SetConnectedCallback(const ConnectedCallback& cb)
    {
        _connected_callback = cb;
    }
    void SetClosedCallback(const ClosedCallback& cb)
    {
        _closed_callback = cb;
    }
    void SetMessageCallback(const MessageCallback& cb)
    {
        _message_callback = cb;
    }
    void SetAnyEventCallback(const AnyEventCallback& cb)
    {
        _event_callback = cb;
    }
    void SetSrvClosedCallback(const ClosedCallback& cb)
    {
        _server_closed_callback = cb;
    }
    //发送数据，数据放到发送缓冲区，启动写事件监控
    void Send(const char* data,size_t len)
    {
        //外界传入的data，可能是个临时的空间，我们现在只是把发送操作压入了任务池，有可能并没有被立即执行
        //因此有可能执行的时候，data指向的空间有可能已经被释放了。
        Buffer buf;
        buf.WriteAndPush(data,len);
        _loop->RunInLoop(std::bind(&Connection::SendInLoop,this,std::move(buf)));
    }
    //提供给组件使用者的接口，并不实际关闭，需要先判断有没有数据待处理
    void Shutdown()
    {
        _loop->RunInLoop(std::bind(&Connection::ShutdownInLoop,this));
    }
    void Release()
    {
        _loop->QueueInLoop(std::bind(&Connection::ReleaseInLoop,this));
    }
    //启动非活跃销毁,并定义延迟事件，添加定时任务
    void EnableInactiveRelease(int sec)
    {
        _loop->RunInLoop(std::bind(&Connection::EnableInactiveReleaseInLoop,this,sec));
    }
    //取消非活跃销毁
    void CancelInactiveRelease()
    {
        _loop->RunInLoop(std::bind(&Connection::CancelInactiveReleaseInLoop,this));
    }
    //切换协议，重置上下文，以及阶段性回调处理函数
    //这个接口必须在EventLoop中执行，防备新事件触发后，切换任务还没有被执行，会导致数据使用原协议处理
    void Upgrade(const Any& context,const ConnectedCallback& conn,const MessageCallback& msg,
                 const ClosedCallback& closed,const AnyEventCallback& event)
    {
        _loop->AssertInLoop();
        _loop->RunInLoop(std::bind(&Connection::Upgrade,this,context,conn,msg,closed,event));
    }

    void Established()
    {
        _loop->RunInLoop(std::bind(&Connection::EstablishedInLoop,this));
    }
};

class Acceptor
{
private:
    Socket _socket;     //创建监听套接字
    EventLoop* _loop;   //对监听套接字进行事件监控
    Channel _channel;   //对监听套接字进行事件管理

    using AcceptCallback = std::function<void(int)>;
    AcceptCallback _accept_callback;
private:
    //监听套接字读事件的回调函数，获取新连接，调用_accept_callback函数进行新连接的处理
    void HandleRead()
    {
        int newfd = _socket.Accept();
        if(newfd < 0)
        {
            return;
        }
        if(_accept_callback)
        {
            _accept_callback(newfd);
        }
    }
    int CreateServer(int port)
    {
        bool ret = _socket.CreateServer(port);
        assert(ret == true);
        return _socket.Fd();
    }
public:
    //注意不能将启动读监控放在构造函数中
    //否则可能启动读监控后立马有事件到来，但是回调函数还没设置，导致新连接无法处理，且资源泄露
    Acceptor(EventLoop* loop,int port)
        :_socket(CreateServer(port))
        ,_loop(loop)
        ,_channel(loop,_socket.Fd())
    {
        _channel.SetReadCallback(std::bind(&Acceptor::HandleRead,this));
    }
    void SetAcceptCallback(const AcceptCallback& cb)
    {
        _accept_callback = cb;
    }
    void Listen()
    {
        _channel.EnableRead();
    }
};

class TcpServer
{
private:
    uint64_t _next_id;                                      //自动增长的连接ID
    int _port;
    int _timeout;                                           //超时时间
    bool _enable_inactive_release;                          //是否启用非活跃销毁
    EventLoop _baseloop;                                    //主线程的EventLoop对象，负责监听事件的处理
    Acceptor _acceptor;                                     //监听套接字管理对象
    LoopThreadPool _pool;                                   //从属EventLoop线程池
    std::unordered_map<uint64_t,PtrConnection> _conns;      //保存管理所有连接对应的shared_ptr对象

private:
    using ConnectedCallback = std::function<void(const PtrConnection&)>;
    using MessageCallback = std::function<void(const PtrConnection&, Buffer *)>;
    using ClosedCallback = std::function<void(const PtrConnection&)>;
    using AnyEventCallback = std::function<void(const PtrConnection&)>;
    using Functor = std::function<void()>;
    ConnectedCallback _connected_callback;
    MessageCallback _message_callback;
    ClosedCallback _closed_callback;
    AnyEventCallback _event_callback;

    //为新连接构造一个Connnection进行管理
    void NewConnection(int fd)
    {
        _next_id++;
        PtrConnection conn(new Connection(_pool.NextLoop(), _next_id, fd));
        conn->SetMessageCallback(_message_callback);
        conn->SetClosedCallback(_closed_callback);
        conn->SetConnectedCallback(_connected_callback);
        conn->SetAnyEventCallback(_event_callback);
        conn->SetSrvClosedCallback(std::bind(&TcpServer::RemoveConnection,this,conn));
        if(_enable_inactive_release) conn->EnableInactiveRelease(_timeout);//启动非活跃超时销毁
        conn->Established();//就绪初始化
        _conns.insert(std::make_pair(_next_id, conn));
    }
    void RemoveConnectionInLoop(const PtrConnection& conn)
    {
        uint64_t id = conn->Id();
        auto it = _conns.find(id);
        if(it != _conns.end())
        {
            _conns.erase(it);
        }
    }
    //从_conns中移除连接信息
    void RemoveConnection(const PtrConnection& conn)
    {
        _baseloop.RunInLoop(std::bind(&TcpServer::RemoveConnectionInLoop,this,conn));
    }
    void RunAfterInLoop(const Functor task,int delay)
    {
        _next_id++;
        _baseloop.TimerAdd(_next_id,delay,task);
    }

public:
    TcpServer(int port)
        :_port(port)
        ,_next_id(0)
        ,_enable_inactive_release(false)
        ,_acceptor(&_baseloop,port)
        ,_pool(&_baseloop)
    {
        _acceptor.SetAcceptCallback(std::bind(&TcpServer::NewConnection,this,std::placeholders::_1));
        _acceptor.Listen();//将监听套接字挂在baseloop上
    }
    //设置线程池数量
    void SetThreadCount(int count)
    {
        _pool.SetThreadCount(count);
    }
    void SetConnectedCallback(const ConnectedCallback&cb)
    {
        _connected_callback = cb;
    }
    void SetMessageCallback(const MessageCallback&cb)
    {
        _message_callback = cb;
    }
    void SetClosedCallback(const ClosedCallback&cb)
    {
        _closed_callback = cb;
    } 
    void SetAnyEventCallback(const AnyEventCallback&cb)
    {
        _event_callback = cb;
    }
    //添加定时任务
    void RunAfter(const Functor task,int delay)
    {
        _baseloop.RunInLoop(std::bind(&TcpServer::RunAfterInLoop,this,task,delay));
    }
    //启动非活跃销毁
    void EnableInactiveRelease(int timeout)
    {
        _timeout = timeout;
        _enable_inactive_release = true;
    }
    void Start()
    {
        _pool.Create();
        _baseloop.Start();
    }
};

void Channel::Remove()
{
    _loop->RemoveEvent(this);
}

void Channel::Update()
{
    _loop->UpdateEvent(this);
}

//添加时间任务
void TimerWheel::TimerAdd(uint64_t id,uint32_t timeout,const TaskFunc& cb)
{
    _loop->RunInLoop(std::bind(&TimerWheel::TimerAddInLoop,this,id,timeout,cb));
}
//刷新某定时任务
void TimerWheel::TimerRefresh(uint64_t id)
{
    _loop->RunInLoop(std::bind(&TimerWheel::TimerRefreshInLoop,this,id));
}
//取消某定时任务
void TimerWheel::TimerCancel(uint64_t id)
{
    _loop->RunInLoop(std::bind(&TimerWheel::TimerCancelInLoop,this,id));
}

class NetWork
{
public:
    NetWork()
    {
        signal(SIGPIPE,SIG_IGN);
    }
};

static NetWork nw;
